package com.jic.point.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.PageResult;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.exception.AppRuntimeException;
import com.jic.point.mapper.*;
import com.jic.point.model.entity.*;
import com.jic.point.model.vo.response.PublMemberBalanceResponse;
import com.jic.point.rest.request.SignData;
import com.jic.point.service.PublMemberBalanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口实现类
 *
 * @author : tzc
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class PublMemberBalanceServiceImpl implements PublMemberBalanceService {

	@Resource
	private PublMemberBalanceMapper mapper;
	@Resource
	private ConfPlatformMapper confPlatformMapper;
	@Resource
	private ConfActivityRuleMapper confActivityRuleMapper;
	@Resource
	private ConfPlatformLogMapper confPlatformLogMapper;
	@Resource
	private ConfActivityRuleLogMapper confActivityRuleLogMapper;


	/**
	 * 新增记录
	 *
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存成功
	 */
	@Override
	public int save(PublMemberBalance request) {
	 int flag = mapper.insert(request);
	 if (flag == 1) {
	   return 1;
	 }else {
	   throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
	 }
	}


	/**
	 * 保存或修改记录信息
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存或修改成功
	 * author tzc
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	public int saveOrUpdate(PublMemberBalance request){
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		try {
			if (request == null) {
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
			}
			if (request.getId() != null) {
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
				int flag = mapper.updateByPrimaryKey(request);
				if(flag == 1){
				  return 1;
				}
			}else{
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
				int flag = mapper.insertSelective(request);
				if(flag == 1){
				  return 1;
				}else{
				  throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
				}
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
		}
	     return -1;
	}

	/**
	 * 删除记录
	 *
	 * @param request 需要删除,含有主键的入参实体类
	 * @return int 是否删除成功
	 */
	@Override
	public int deleteByPrimaryKey(PublMemberBalance request) {
		int flag = mapper.deleteByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
	    }
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request 含有主键的逻辑删除实体类
	 * @return int 是否逻辑删除成功
	 */
	@Override
	public int deleteByPrimaryKeyLogically(PublMemberBalance request) {
		request.setDeleteFlag(1);
		int flag = mapper.updateByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
	    }
	}


	/**
	 * 修改
	 *
	 * @param request
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(PublMemberBalance request){
		try {
			log.info("修改记录");
			PublMemberBalance param = new PublMemberBalance();
			BeanUtils.copyProperties(request, param);
			int flag = mapper.updateByPrimaryKeySelective(param);
	        if (flag == 1) {
	         return 1;
	        }else {
	          throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
	        }
		} catch (Exception e) {
			log.error("修改记录失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改记录失败");
		}
	}

	/**
	 * 增加容错积分
	 * @param publMemberBalance
	 * @return
	 */
	@Transactional
	@Override
	public int userIdByPrimaryKey(PublMemberBalance publMemberBalance,String type) {
		if(publMemberBalance==null){
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"参数为空");
		}
		PublMemberBalance balance = mapper.ByUserIDPrimaryKey(publMemberBalance);
		balance.setTotal(balance.getTotal().add(publMemberBalance.getTotal()));
		balance.setAvailable(balance.getAvailable().add(publMemberBalance.getTotal()));
		Integer i = mapper.userIdByPrimaryKey(balance);
		if(i!=1){
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"增加积分失败");
		}
		//type =0 表示这是平台
		if("0".equals(type)){
			ConfPlatform confPlatform=new ConfPlatform();
			confPlatform.setId(publMemberBalance.getId());
			//根据id查询到对应的平台
			ConfPlatform confPlatform1 = confPlatformMapper.selectByPrimaryKey(confPlatform);
			//减去对应的积分
			confPlatform1.setTotal(confPlatform1.getTotal().subtract(publMemberBalance.getTotal()));
			confPlatform1.setAvailable(confPlatform1.getAvailable().subtract(publMemberBalance.getTotal()));
			int primaryKey = confPlatformMapper.updateByPrimaryKey(confPlatform1);
			if(primaryKey!=1){
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
			}
			ConfPlatformLog confPlatformLog=new ConfPlatformLog();
			BeanUtils.copyProperties(confPlatform1,confPlatformLog);
			confPlatformLog.setId(0L);
			confPlatformLog.setDeptId(confPlatform1.getDeptId());
			confPlatformLog.setBdCode(confPlatform1.getBdCode());
			confPlatformLog.setPlatformCode(confPlatform1.getCode());
			confPlatformLog.setPointType(5);
			confPlatformLog.setDeliveryType(2);
			confPlatformLog.setType(2);
			confPlatformLog.setAmount(publMemberBalance.getTotal());
			confPlatformLog.setCreator(publMemberBalance.getCreator());
			confPlatformLog.setCreateTime(new Date());
			int selective = confPlatformLogMapper.insertSelective(confPlatformLog);
			if(selective!=1){
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"增加流水失败");

			}
			//type =1 表示这是活动规则
		}else if("1".equals(type)){
			ConfActivityRule confActivityRule=new ConfActivityRule();
			confActivityRule.setId(publMemberBalance.getId());
			ConfActivityRule confActivityRule1 = confActivityRuleMapper.selectByPrimaryKey(confActivityRule);
			confActivityRule1.setTotal(confActivityRule1.getTotal().subtract(publMemberBalance.getTotal()));
			confActivityRule1.setAvailable(confActivityRule1.getAvailable().subtract(publMemberBalance.getTotal()));
			int i1 = confActivityRuleMapper.updateByPrimaryKey(confActivityRule1);
			if(i1!=1){
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"活动修改失败");
			}
			ConfActivityRuleLog log=new ConfActivityRuleLog();
			BeanUtils.copyProperties(confActivityRule1,log);
			log.setId(0L);
			log.setAmount(publMemberBalance.getTotal());
			log.setDeliveryType(2);
			log.setType(2);
			log.setPointType(5);
			log.setBdCode(confActivityRule1.getBdCode());
			log.setPlatformCode(confActivityRule1.getPlatformCode().toString());
			log.setActivityRuleCode(confActivityRule1.getCode());
			log.setCreateTime(new Date());
			log.setCreator(publMemberBalance.getCreator());
			log.setDeleteFlag(0);
			int selective = confActivityRuleLogMapper.insertSelective(log);
			if(selective!=1){
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"活动流水新增失败");
			}
		}
		return i;


	}



	/**
	 * 记录详情
	 *
	 * @param request 查询的入参实体类
	 * @return 数据库查询到的实体类
	 */
	@Override
	public PublMemberBalance getByPrimaryKey(PublMemberBalance request) {
		return mapper.selectByPrimaryKey(request);
	}


	/**
	 * 分页查询
	 *
	 * @param request 分页查询入参实体类
	 * @return 含有分页信息的实体类列表
	 */
	@Override
	public PageInfo<PublMemberBalance> listPageBySelective(PublMemberBalance request, int pageNum, int pageSize) {
	PageHelper.startPage(pageNum, pageSize);
	PageHelper.orderBy(" create_time desc");
	List<PublMemberBalance> list = mapper.listPageBySelective(request);
	PageInfo pageInfo = new PageInfo(list);
	PageResult<PublMemberBalance> result = new PageResult<>();
	result.setTotal(pageInfo.getTotal());
	result.setRows(list);
	return new PageInfo(list);
	}

	/**
	 * 不分页查询
	 *
	 * @param request 不分页查询入参实体类
	 * @return 数据库查到的实体类列表
	 */
	@Override
	public List<PublMemberBalance> listAllRecord(PublMemberBalance request) {
		//分页处理
		request.setDeleteFlag(0);
		return mapper.selectBySelective(request);
	}

	@Override
	public List<PublMemberBalanceResponse> queryMemberByCode(PublMemberBalance member) {
		List<PublMemberBalance> publMemberBalanceResponses = mapper.queryMemberByCode(member);
		List<PublMemberBalanceResponse> collect = publMemberBalanceResponses.stream().map(item -> {
		PublMemberBalanceResponse publMemberBalanceResponse = new PublMemberBalanceResponse();
		BeanUtils.copyProperties(item, publMemberBalanceResponse);
			return publMemberBalanceResponse;
		}).collect(Collectors.toList());
		return collect;
	}

	@Override
	public Integer addPoint(PublMemberBalance member) {
		return mapper.addPoint(member);
	}

	@Override
	public PublMemberBalance selectByCode(String memberCode) {
		return mapper.selectByCode(memberCode);
	}

	@Override
	public BigDecimal getUserPoint(Long id) {
		BigDecimal point = mapper.getUserPoint(id);
		return point;
	}

    @Override
    public List<PublMemberBalance> queryPublMemberBalanceByCode(SignData signData) {
        return mapper.queryPublMemberBalanceByCode(signData);
    }

    @Override
    public int consumePoint(PublMemberBalance publMemberBalance) {
        return mapper.consumePoint(publMemberBalance);
    }


}
